package com.example.demo.config;

import com.example.demo.realm.MyRealm;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Configuration
public class ShiroConfig {

    @Bean
    public MyRealm myAuthReam() {
        log.info("===MyRealm注册===");
        return new MyRealm();
    }

    @Bean
    public SecurityManager securityManager() {
        log.info("===securityManager注册===");
        return new DefaultWebSecurityManager(myAuthReam());
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("/success");
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
        Map<String, String> filterChainMap = new LinkedHashMap<>();
        filterChainMap.put("/static/**", "anon");
        filterChainMap.put("/login", "anon");
        filterChainMap.put("/user/admin*", "authc");
        filterChainMap.put("/user/student*/**", "roles[admin]");
        filterChainMap.put("/user/teacher*/**", "perms[\"user:create\"]");
        filterChainMap.put("/logout", "logout");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainMap);
        log.info("===ShiroFilterFactoryBean注册===");
        return shiroFilterFactoryBean;
    }
}
